package com.gzx.plugin.tjzy.modular.sms.whitelist.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.gzx.plugin.tjzy.modular.sms.whitelist.bo.GzxSmsWhitelistAddOrEditBo;
import com.gzx.plugin.tjzy.modular.sms.whitelist.bo.GzxSmsWhitelistImportBo;
import com.gzx.plugin.tjzy.modular.sms.whitelist.bo.GzxSmsWhitelistQueryBo;
import com.gzx.plugin.tjzy.modular.sms.whitelist.entity.GzxSmsWhitelist;
import com.gzx.plugin.tjzy.modular.sms.whitelist.mapper.GzxSmsWhitelistMapper;
import com.gzx.plugin.tjzy.modular.sms.whitelist.service.GzxSmsWhitelistService;
import com.gzx.plugin.tjzy.modular.sms.whitelist.vo.GzxSmsWhitelistExcelVo;
import com.gzx.plugin.tjzy.modular.sms.whitelist.vo.GzxSmsWhitelistVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.util.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author xbl
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxSmsWhitelistServiceImpl extends ServiceImpl<GzxSmsWhitelistMapper, GzxSmsWhitelist> implements GzxSmsWhitelistService {

    /**
     * 分页查询短信白名单
     */
    @DS("sms")
    @Override
    public Page<GzxSmsWhitelistVo> pageList(GzxSmsWhitelistQueryBo smsWhitelistQueryBo) {
        return baseMapper.selectVoPage(new Page<>(smsWhitelistQueryBo.getCurrent(), smsWhitelistQueryBo.getSize()),
                Wrappers.<GzxSmsWhitelist>lambdaQuery()
                        .eq(StringUtils.isNotBlank(smsWhitelistQueryBo.getProductName()), GzxSmsWhitelist::getProductName, smsWhitelistQueryBo.getProductName())
                        .eq(StringUtils.isNotBlank(smsWhitelistQueryBo.getProductCode()), GzxSmsWhitelist::getProductCode, smsWhitelistQueryBo.getProductCode())
                        .eq(StringUtils.isNotBlank(smsWhitelistQueryBo.getPhone()), GzxSmsWhitelist::getPhone, CommonCryptogramUtil.doSm1AesEncrypt(smsWhitelistQueryBo.getPhone()))
                        .eq(StringUtils.isNotBlank(smsWhitelistQueryBo.getCurrentMonth()), GzxSmsWhitelist::getCurrentMonth, smsWhitelistQueryBo.getCurrentMonth())
                        .orderByDesc(GzxSmsWhitelist::getId));
    }

    /**
     * 短信白名单新增或者修改
     */
    @DS("sms")
    @Override
    public void addOrEdit(GzxSmsWhitelistAddOrEditBo smsWhitelistAddOrEditBo) {
        GzxSmsWhitelist smsWhitelist = MapstructUtils.convert(smsWhitelistAddOrEditBo, GzxSmsWhitelist.class);
        if (smsWhitelistAddOrEditBo.getId() == null) {
            baseMapper.insert(smsWhitelist);
        } else {
            baseMapper.updateById(smsWhitelist);
        }
    }

    /**
     * 删除短信白名单
     */
    @DS("sms")
    @Override
    public void delete(Long id) {
        baseMapper.deleteById(id);
    }

    /**
     * 根据当月查询短信白名单
     */
    @DS("sms")
    public List<GzxSmsWhitelist> queryByCurrentMonth(GzxSmsWhitelistQueryBo queryBo) {
        return baseMapper.selectList(Wrappers.<GzxSmsWhitelist>lambdaQuery()
                .eq(GzxSmsWhitelist::getCurrentMonth, queryBo.getCurrentMonth())
                .eq(GzxSmsWhitelist::getProductCode, queryBo.getProductCode())
        );
    }

    /**
     * 短信白名单导入
     */
    @DS("sms")
    @Override
    public void importExcel(GzxSmsWhitelistImportBo importBo, MultipartFile multipartFile) {
        if (ObjectUtils.isEmpty(importBo) || StringUtils.isEmpty(importBo.getCurrentMonth()) || StringUtils.isEmpty(importBo.getProductCode()) || StringUtils.isEmpty(importBo.getProductName())) {
            throw new CommonException("参数为空");
        }
        List<GzxSmsWhitelistExcelVo> voList = CommonExcelUtil.importExcel(multipartFile, GzxSmsWhitelistExcelVo.class).stream().toList();
        List<GzxSmsWhitelist> whitelists = MapstructUtils.convert(voList, GzxSmsWhitelist.class);
        if (CollUtil.isEmpty(whitelists)) {
            throw new CommonException("Excel为空");
        }
        log.info("白名单导入去重之前多少条 {} ", whitelists.size());
        //列表按照手机号去重
        whitelists = whitelists.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(
                                GzxSmsWhitelist::getPhone,
                                whitelist -> whitelist,
                                (existing, replacement) -> existing
                        ),
                        map -> new ArrayList<>(map.values())
                ));

        log.info("白名单导入去重之后多少条 {} ", whitelists.size());

        SaBaseLoginUser user = StpLoginUserUtil.getLoginUser();

        String currTime = CommonDateUtil.getCurrentTimeStr();
        List<List<GzxSmsWhitelist>> bacthList = Lists.partition(whitelists, IntConstant.VALUE_1000);
        for (List<GzxSmsWhitelist> whitelist : bacthList) {
            String batchSql = whitelist.stream()
                    .map(s -> String.format("('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
                            escapeSql(importBo.getProductName()),
                            escapeSql(importBo.getProductCode()),
                            escapeSql(importBo.getCurrentMonth()),
                            escapeSql(CommonCryptogramUtil.doSm1AesEncrypt(s.getPhone())),
                            escapeSql(user.getTenantId()),
                            escapeSql(user.getId()),
                            escapeSql(currTime)
                    ))
                    .collect(Collectors.joining(", ")).replace("'null'", "null");
            baseMapper.insertBatchSql(batchSql);
            CommonSleepUtil.sleep(IntConstant.VALUE_100);
        }
    }

}
